<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\facade\Db;

class DataProjectTort extends AdminBase
{
    public function index()
    {
        $param = $this->request->param();
        $db = Db::name('data_project_tort'); 
        if(!empty($param['parent_typeid'])) {
            $db = $db->where('parent_typeid',$param['parent_typeid']);
            if(!empty($param['typeid'])){
                $db = $db->where('typeid',$param['typeid']);
            }
        }
        if(!empty($param['kw'])){
            $db = $db->where('title','like','%'.$param['kw'].'%');
        }
        $list = $db->order('id desc')->paginate(['list_rows'=> 100,'query' => $param]);
        $count = $list->total();
        $parent_typelist = Db::name('data_type')->where('level',1)->select()->toArray();
        $typelist = Db::name('data_type')->where([
            'level' => 2,
            'pid' => $param['parent_typeid']
        ])->select()->toArray();
        return view('',['list'=>$list,'count'=>$count,'param'=>$param,'parent_typelist'=>$parent_typelist,'typelist'=>$typelist]);
    }

    public function add()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            if(!empty($param['parent_typeid'])) $param['top_typeid'] = get_typepid($param['parent_typeid']);
            $result = Db::name('data_project_tort')->insert($param);
            if( $result ) {
                xn_add_admin_log('添加侵权项目');
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        $parent_typelist = Db::name('data_type')->where('level',1)->select()->toArray();
        return view('form',['parent_typelist'=>$parent_typelist]);
    }

    public function edit()
    {
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            if(!empty($param['parent_typeid'])) $param['top_typeid'] = get_typepid($param['parent_typeid']);
            $result = Db::name('data_project_tort')->update($param);
            if( $result ) {
                xn_add_admin_log('修改侵权项目');
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }

        $id = $this->request->get('id');
        $data = Db::name('data_project_tort')->where('id',$id)->find();
        $parent_typelist = Db::name('data_type')->where('level',1)->select()->toArray();
        $typelist = Db::name('data_type')->where([
            'level' => 2,
            'pid' => $data['parent_typeid']
        ])->select()->toArray();
        return view('form',['data'=>$data,'parent_typelist'=>$parent_typelist,'typelist'=>$typelist]);
    }

    public function delete()
    {
        $id = intval($this->request->get('id'));
        !($id>0) && $this->error('参数错误');
        Db::name('data_project_tort')->delete($id);
        xn_add_admin_log('删除侵权项目');
        $this->success('删除成功');
    }

    public function deleteAll(){
        $ids = $this->request->get('ids');
        ($ids=='') && $this->error('参数错误');
        $ids = explode(',',$ids);
        Db::name('data_project_tort')->delete($ids);
        xn_add_admin_log('批量删除侵权项目');
        $this->success("删除成功");
    }

    public function import(){
        $file = request()->file('file');
        $savename = \think\facade\Filesystem::putFileAs( 'excel', $file, 'project.xlsx');
        if(!$savename){
            return json(['status'=>'0','msg'=>'文件上传失败!']);
        }
        $filePath = \think\facade\Filesystem::path($savename);
        
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)) {
                return json(['status'=>'0','msg'=>'No Excel!']);
            }
        }

        $PHPExcel = $PHPReader->load($filePath);
        $currentSheet = $PHPExcel->getSheet(0);
        //$allColumn = $currentSheet->getHighestColumn();
        $allRow = $currentSheet->getHighestRow();

        $limitNum = 10;
        $limitPage = ceil($allRow / $limitNum);
        $count = 0;
        for($i=0;$i<$limitPage;$i++){
            $limitIndex = $i * $limitNum;
            $limitEnd = $limitIndex + $limitNum;
            if($i == 0){
                $limitIndex = 2;
            }
            if($limitEnd >= $allRow){
                $limitEnd = $allRow+1;
            }
            for($currentRow = $limitIndex; $currentRow < $limitEnd; $currentRow++) {
                $dalei = $currentSheet->getCell('A'.$currentRow)->getValue();
                $xiaolei = $currentSheet->getCell('B'.$currentRow)->getValue();
                $data['title'] = $currentSheet->getCell('C'.$currentRow)->getValue();
                $data['alias'] = $currentSheet->getCell('D'.$currentRow)->getValue();
                if(empty($data['title'])) continue;
                
                $type1 = Db::name('data_type')->field('id,alias')->where([
                    'level' => 1,
                    'title' => $dalei
                ])->find();
                if($type1) {
                    $data['parent_typeid'] = $type1['id'];
                    $data['top_typeid'] = get_typepid($data['parent_typeid']);
                }
                $type2 = Db::name('data_type')->field('id,alias')->where([
                    'level' => 2,
                    'title' => $xiaolei
                ])->find();
                if($type2) $data['typeid'] = $type2['id'];
                if(empty($data['alias'])){
                    $data['alias'] = $data['title'];
                }
                $r = Db::name('data_project_tort')->where([
                    'typeid' => $data['typeid'],
                    'title' => $data['title']
                ])->find();
                if(!$r){
                    $insertId = Db::name('data_project_tort')->insertGetId($data);
                    if($insertId){
                        Db::name('data_project')->where([
                            ['tort', '=', 0],
                            ['title', '=', $data['title']]
                        ])->update(['tort'=>1]);
                        $count++;
                    }
                }
            }
        }
        return json(['status'=>'1','msg'=>'成功执行 '.$count.' 条数据']);
    }

    public function filterProject(){
        $start = intval($this->request->get('start'));
        $end = intval($this->request->get('end'));
        $flag = intval($this->request->get('flag'));
        if(empty($start) || empty($end)){
            $start = Db::name('data_project_tort')->field('id')->order('id asc')->find();
            $end = Db::name('data_project_tort')->field('id')->order('id desc')->find();
            if(!empty($start) && !empty($end)){
                $start = $start['id'];
                $end = $end['id'];
            }else{
                return json([
                    'status' => 0,
                    'msg' => '没有可匹配的数据'
                ]);
            }
        }
        if($start > $end){
            return json([
                'status' => 0,
                'msg' => '执行完毕'
            ]);
        }
        $limit = 50;
        $nextStart = ($start+$limit);
        $map[] = ['id','>=',$start];
        $map[] = ['id','<',$nextStart];
        $list = Db::name('data_project_tort')->where($map)->field('id,title,typeid,alias')->order('id asc')->select()->toArray();
        if(!empty($list)){
            foreach($list as $v){
                if(empty($v['alias'])){
                    continue;
                }
                $v['alias'] = str_replace('，',',',$v['alias']);
                $arr = explode(',',$v['alias']);
                foreach($arr as $vv){
                    $r = Db::name('data_project')->where([
                        ['tort', '=', 0],
                        ['typeid', '=', $v['typeid']],
                        ['title', 'like', '%'.$vv.'%']
                    ])->update(['tort' => 1]);
                }
            }
        }
        $map2[] = ['id','>=',$nextStart];
        $_nextStart = Db::name('data_project_tort')->where($map2)->field('id')->order('id asc')->find();
        if(!empty($_nextStart)){
            $_start = $_nextStart['id'];
        }else{
            return json([
                'status' => 0,
                'msg' => '全部执行完毕'
            ]);
        }
        // echo '<script>window.location.href="http://www.xnadmin.site/admin/DataProject/matchingCompany/?start='.$_start.'&end='.$end.'";</script>';
        return json([
            'status' => 1,
            'msg' => '正在执行，ID:'.$start.'至'.$nextStart.'，结束ID:'.$end,
            'data' => ['start' => $_start, 'end' => $end]
        ]);
    }

}
